package middleware

import (
	"gitee.com/chejiangyi/bsfgo/core/base2"
	"gitee.com/chejiangyi/bsfgo/core/utils"
	"gitee.com/chejiangyi/bsfgo/gin2/template2"
	"github.com/gin-gonic/gin"
	"path/filepath"
	"strings"
)

type TemplateMiddleware struct{}

func (*TemplateMiddleware) GetOrder() float64 {
	return -90
}
func (m *TemplateMiddleware) Enabled() bool {
	return base2.BsfConfigInstance.GetTemplateEnabled()
}
func (*TemplateMiddleware) Middleware(r *gin.Engine) {
	if base2.BsfConfigInstance.GetTemplateLoadHTMLGlobEnabled() {
		//模板
		match := base2.BsfConfigInstance.GetTemplateLoadHTMLGlobMatch()
		r.LoadHTMLGlob(match)
		utils.LogUtil.Info("[TemplateMiddleware]web template渲染已开启全局模板缓存,模板位置:%v", match)
	}
	if base2.BsfConfigInstance.GetTemplatePageCacheRenderEnabled() {
		//缓存基础模板路径
		files, _ := filepath.Glob(base2.BsfConfigInstance.GetTemplatePageCacheRenderShardTemplateFileMatch())
		template2.ShardTemplateFileNames = files
		utils.LogUtil.Info("[TemplateMiddleware]web template渲染已开启页面模板缓存,共享模板:%v", strings.Join(files, ","))
	}
	if base2.BsfConfigInstance.GetTemplateStaticEnabled() {
		//静态目录
		js := base2.BsfConfigInstance.GetTemplateStaticJsPath()
		css := base2.BsfConfigInstance.GetTemplateStaticCssPath()
		images := base2.BsfConfigInstance.GetTemplateStaticImagesPath()
		favicon := base2.BsfConfigInstance.GetTemplateStaticFavicon()
		r.Static("/js", js) //  定义静态资源路由与实际目录映射关系
		r.Static("/css", css)
		r.Static("/images", images)
		if favicon != "" {
			r.GET("/favicon.ico", func(c *gin.Context) {
				c.Header("Content-Type", "image/x-icon")
				c.Header("Cache-Control", "public, max-age=31536000")
				c.File(base2.BsfConfigInstance.GetTemplateStaticFavicon())
			})
		}
		utils.LogUtil.Info("[TemplateMiddleware]web static文件已开启,文件夹映射:%v,%v,%v,%v", js, css, images, favicon)
	}

	utils.LogUtil.Info("TemplateMiddleware已开启")
}
